//
//  KLScanCodeViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/5/16.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLScanCodeViewController.h"
#import "KLHelp.h"
#import "Masonry.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "KLHttpAPI.h"
#import "SSKeychain.h"

@interface KLScanCodeViewController ()<ZBarReaderViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
{
    UIImagePickerController *picker;//打开相册
}
@property(nonatomic,strong)UIImageView *scanImgView;//扫描中间上下滑动的view

@property(nonatomic,strong)NSString *lockName;  //锁别名
@property(nonatomic,strong)NSString *publicKey; //公钥
@property(nonatomic,strong)NSString *lockUname; //锁原始名

@end

@implementation KLScanCodeViewController

-(void)viewWillAppear:(BOOL)animated{
    [self timeSet];
}

-(void)viewDidAppear:(BOOL)animated{
    picker = [[UIImagePickerController alloc] init];
    picker.allowsEditing = YES;
    picker.delegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self naveSet];
    
    self.readerView = [[ZBarReaderView alloc]init];
    self.readerView.readerDelegate = self;
    self.readerView.frame = CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height);
    //关闭闪光灯
    self.readerView.torchMode = 0;
    
    //扫描区域
    CGRect scanMaskRect = CGRectMake(40, 40, UI_View_Width-80, UI_View_Width-80);
    //扫描区域计算
    self.readerView.scanCrop = [self getScanCrop:scanMaskRect readerViewBounds:self.readerView.bounds];
    
    [self.view addSubview:self.readerView];
    [self.readerView start];

    //扫描中间框
    UIImageView *scanView = [[UIImageView alloc]init];
    [scanView setImage:[UIImage imageNamed:@"R扫描中间框.png"]];
    [scanView setFrame:CGRectMake(40, 20, UI_View_Width-80, UI_View_Width-80)];
    [self.view addSubview:scanView];
    
    //底部
    UIView *downView = [[UIView alloc]init];
    [downView setFrame:CGRectMake(0, UI_View_Height-200, UI_View_Width, 140)];
    [downView setAlpha:0.5];
    [downView setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:downView];
    
    //开灯
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"R扫描开灯.png"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(openLight:) forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(50);
        make.right.mas_equalTo(-UI_View_Width/5);
        make.bottom.mas_equalTo(-40);
    }];
    
    UILabel *labRight = [[UILabel alloc]init];
    labRight.backgroundColor = [UIColor clearColor];
    labRight.textAlignment = NSTextAlignmentCenter;
    labRight.font = [UIFont systemFontOfSize:14];
    labRight.textColor = BB_White_Color;
    labRight.text = @"开灯";
    [downView addSubview:labRight];
    [labRight mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(17);
        make.right.mas_equalTo(-UI_View_Width/5);
        make.bottom.mas_equalTo(-18);
    }];
    
    //相册
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"R扫描相册.png"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(openPhotoShop:) forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(UI_View_Width/5);
        make.bottom.mas_equalTo(-40);
    }];
    
    UILabel *labLeft = [[UILabel alloc]init];
    labLeft.backgroundColor = [UIColor clearColor];
    labLeft.textAlignment = NSTextAlignmentCenter;
    labLeft.font = [UIFont systemFontOfSize:14];
    labLeft.textColor = BB_White_Color;
    labLeft.text = @"相册";
    [downView addSubview:labLeft];
    [labLeft mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(17);
        make.left.mas_equalTo(UI_View_Width/5);
        make.bottom.mas_equalTo(-18);
    }];
    
    //上下滑动框
    self.scanImgView = [[UIImageView alloc]init];
    [self.scanImgView setFrame:CGRectMake(66, 54, UI_View_Width-132, 8)];
    [self.scanImgView setImage:[UIImage imageNamed:@"R扫描上下长条.png"]];
    [self.view addSubview:self.scanImgView];
}

#pragma mark -方法体内方法
-(void)timeSet{
    [self.scanImgView setFrame:CGRectMake(66, 54, UI_View_Width-132, 8)];
    
    [UIView animateWithDuration:2 animations:^{
        [self.scanImgView setFrame:CGRectMake(66, UI_View_Width-76, UI_View_Width-132, 8)];
    }completion:^(BOOL finished){
         [self timeSet];
     }];
}

//开灯
-(void)openLight:(id)sender{
    if (self.readerView.torchMode == 1){
        self.readerView.torchMode = 0;
    }else{
        self.readerView.torchMode = 1;
    }
}

//相册
-(void)openPhotoShop:(id)sender{
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
    [self presentViewController:picker animated:YES completion:nil];
}

//初始化导航栏
-(void)naveSet{
    self.navigationController.navigationBarHidden = NO;
    self.title = @"扫描二维码";
    self.view.backgroundColor = [UIColor whiteColor];
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
}-(void)doBack:(id)sender{
    [self.readerView stop];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -ZBarSDK的代理方法
-(void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image{
    for (ZBarSymbol *symbol in symbols) {
        NSLog(@"扫描到的数据为:%@,长度为:%zd", symbol.data,symbol.data.length);
        NSString *gongyue = [symbol.data substringFromIndex:14];
        if(gongyue.length == 216){
            self.publicKey = gongyue;
            NSString *modelStr = [symbol.data substringWithRange:NSMakeRange(0, 4)];
            NSString *numberStr = [symbol.data substringWithRange:NSMakeRange(10, 4)];
            self.lockName = [NSString stringWithFormat:@"KissLock%@%@",modelStr,numberStr];
            self.lockUname = [NSString stringWithFormat:@"KissLock%@%@",modelStr,numberStr];
            NSLog(@"公钥:%@,锁名:%@",self.publicKey,self.lockUname);
            //扫描到的公钥存储于本地
            [self memoryPublicKeysWithKey:self.lockUname value:self.publicKey];
            
            //添加锁
            [KLHelp showHUDAddedTo:self.view title:@"正在添加..." details:nil animated:YES];
            [KLHttpAPI requestAddLockWithLockName:self.lockName lockUname:self.lockUname code:self.publicKey completionHandler:^(NSString *responseString) {
                NSLog(@"添加锁返回数据:%@",responseString);
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                
                NSDictionary *info = [KLHelp dictionaryWithJsonString:responseString];
                NSString *msg = [info objectForKey:@"msg"];
                [JRToast showWithText:msg];
                NSString *isSuccess = [info objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    NSDictionary *idInfo = [info objectForKey:@"infor"];
                    [[NSUserDefaults standardUserDefaults] setObject:idInfo forKey:self.lockUname];
                    //扫描成功时发送刷新锁列表通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"scanSuccess" object:nil userInfo:nil];
                }
                [self.readerView stop];
                [self.navigationController popViewControllerAnimated:YES];
            } errorHandler:^(NSString *error) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                [self.readerView stop];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [JRToast showWithText:@"二维码格式有误"];
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [self.readerView stop];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds{
    CGFloat x,y,width,height;
    
    x = rect.origin.y / readerViewBounds.size.height;
    y = 1 - (rect.origin.x + rect.size.width) / readerViewBounds.size.width;
    width = (rect.origin.y + rect.size.height) / readerViewBounds.size.height;
    height = 1 - rect.origin.x / readerViewBounds.size.width;
    
    return CGRectMake(x, y, width, height);
}

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -图片选择器的代理
- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    alert.delegate = self;
    
    ZBarReaderController *read = [ZBarReaderController new];
    CGImageRef cgImageRef = image.CGImage;
    for(ZBarSymbol* symbol in [read scanImage:cgImageRef]){
        if(symbol.data.length < 15){
            [alert setTitle:@"二维码格式有误"];
            [alert show];
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            return ;
        }
        NSLog(@"*******%@*********",symbol.data);
        NSString *gongyue = [symbol.data substringFromIndex:14];
        if(gongyue.length == 216){
            self.publicKey = gongyue;
            NSString *modelStr = [symbol.data substringWithRange:NSMakeRange(0, 4)];
            NSString *numberStr = [symbol.data substringWithRange:NSMakeRange(10, 4)];
            self.lockName = [NSString stringWithFormat:@"KissLock%@%@",modelStr,numberStr];
            self.lockUname = [NSString stringWithFormat:@"KissLock%@%@",modelStr,numberStr];
            NSLog(@"公钥:%@,锁名:%@",self.publicKey,self.lockUname);
            //扫描到的公钥存储于本地
            [self memoryPublicKeysWithKey:self.lockUname value:self.publicKey];
            
            [KLHelp showHUDAddedTo:self.view title:@"正在添加..." details:nil animated:YES];
            [KLHttpAPI requestAddLockWithLockName:self.lockName lockUname:self.lockUname code:self.publicKey completionHandler:^(NSString *responseString) {
                NSLog(@"添加钥匙返回数据:%@",responseString);
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                
                NSDictionary *info = [KLHelp dictionaryWithJsonString:responseString];
                NSString *msg = [info objectForKey:@"msg"];
                [alert setTitle:msg];
                [alert show];
                NSString *isSuccess = [info objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    NSDictionary *idInfo = [info objectForKey:@"infor"];
                    [[NSUserDefaults standardUserDefaults] setObject:idInfo forKey:self.lockUname];
                    //扫描成功时发送刷新锁列表通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"scanSuccess" object:nil userInfo:nil];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp hideAllHUDsForView:self.view animated:YES];
            }];
        }else{
            [alert setTitle:@"二维码格式有误"];
            [alert show];
            [KLHelp hideAllHUDsForView:self.view animated:YES];
        }
    }
    
    if([read scanImage:cgImageRef] == nil){
        [alert setTitle:@"照片中未识别到二维码"];
        [alert show];
    }    
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 公钥存储本地
-(void)memoryPublicKeysWithKey:(NSString *)key value:(NSString *)value{
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    NSDictionary *keysDic = [KLHelp dictionaryWithJsonString:jsonStr];
    NSMutableDictionary *publickeysdic;
    if(keysDic == nil){
        publickeysdic = [NSMutableDictionary dictionary];
    }else{
        publickeysdic = [NSMutableDictionary dictionaryWithDictionary:keysDic];
    }
    [publickeysdic setObject:value forKey:key];
    [SSKeychain setPassword:[KLHelp dictionaryToJson:publickeysdic] forService:@"com.kisslock.guoyang" account:@"publickeysdic"];
}

#pragma mark - uiaalerView的代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"bunttonIndex:%zd",buttonIndex);
    if(buttonIndex == 0){
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
@end
